package com.link.ppt.View;

import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baoyz.actionsheet.ActionSheet;
import com.link.ppt.App.App;
import com.link.ppt.Base.BaseActivity;
import com.link.ppt.Model.Bean.BaseBean;
import com.link.ppt.Model.Bean.ExpertFieldBean;
import com.link.ppt.Model.Bean.ExpertFieldEntity;
import com.link.ppt.Model.Bean.PPTResponseBean;
import com.link.ppt.Model.IPPTModel;
import com.link.ppt.Model.IUserModel;
import com.link.ppt.Model.Impl.PPTModelImpl;
import com.link.ppt.Model.Impl.UserModelImpl;
import com.link.ppt.R;
import com.link.ppt.Utils.CommonSubscriber;
import com.link.ppt.Utils.DeviceUtils;
import com.link.ppt.Utils.PreferenceUtils;
import com.link.ppt.Utils.RetrofitUploadFileParameterBuilder;
import com.link.ppt.Utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;
import rx.functions.Action0;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by liucxu on 2018/1/31.
 */

public class SelectPPTIndustry extends BaseActivity {

    @BindView(R.id.layout_back)
    LinearLayout back_layout;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.layout_industry)
    RelativeLayout layout_industry;
    @BindView(R.id.tv_industry)
    TextView tv_industry;

    private ExpertFieldBean industry;
    private long industryId;


    private boolean isSelectPhoto;
    private String pptTitle;
    private String pptKeyWord;
    private String pptUrl;
    private String[] photos;
    private List<String> paths = new ArrayList<>();
    private String pptId;
    private String shares = "";

    private IUserModel model;
    private IPPTModel pptModel;

    @Override
    public int getLayoutId() {
        return R.layout.activity_select_industry_ppt;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        tv_title.setText(getResources().getString(R.string.ppt_string_53));
        model = new UserModelImpl();
        pptModel = new PPTModelImpl();
        requestIndustry();
        isSelectPhoto = getIntent().getBooleanExtra("isSelectPhoto", true);
        shares = getIntent().getStringExtra("shares");
        if (TextUtils.isEmpty(shares)) {
            shares = "";
        }
        if (!isSelectPhoto) {
            pptTitle = getIntent().getStringExtra("pptTitle");
            pptKeyWord = getIntent().getStringExtra("pptKeyWord");
            pptUrl = getIntent().getStringExtra("pptUrl");
        } else {
            pptTitle = getIntent().getStringExtra("pptTitle");
            pptKeyWord = getIntent().getStringExtra("pptKeyWord");
            photos = getIntent().getStringArrayExtra("photos");
            Collections.addAll(paths, photos);
        }
    }

    @Override
    public void setupData() {

    }

    private void requestIndustry() {
        model.requestIndustry().doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<ExpertFieldBean>() {
            @Override
            public void onSuccess(ExpertFieldBean response) {
                hideProgress();
                industry = response;
                if (industry.getCode() == 0) {
                    tv_industry.setText(industry.getIndustryList().get(0).getIndustryName());
                    industryId = industry.getIndustryList().get(0).getIndustryId();
                } else {
                    ToastUtils.showShortToast(SelectPPTIndustry.this, response.getDesc());
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                ToastUtils.showShortToast(SelectPPTIndustry.this, response.getDesc());
            }
        });
    }

    @OnClick({R.id.layout_back, R.id.layout_industry, R.id.tv_next_step})
    void doClicks(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.layout_back:
                App.GetInstance().finishActivity(this);
                break;
            case R.id.layout_industry:
                selectIndustry();
                break;
            case R.id.tv_next_step:
                publishPPT();
                break;
        }
    }

    private void selectIndustry() {
        if (industry != null && industry.getIndustryList().size() > 0) {
            String[] mOtherButtonTitles = new String[industry.getIndustryList().size()];
            int index = 0;
            for (ExpertFieldEntity entity : industry.getIndustryList()) {
                mOtherButtonTitles[index] = entity.getIndustryName();
                index++;
            }
            ActionSheet.createBuilder(SelectPPTIndustry.this, getSupportFragmentManager())
                    .setCancelButtonTitle(getResources().getString(R.string.ppt_string_40))
                    .setOtherButtonTitles(mOtherButtonTitles)
                    .setCancelableOnTouchOutside(true)
                    .setListener(new ActionSheet.ActionSheetListener() {
                        @Override
                        public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
                        }

                        @Override
                        public void onOtherButtonClick(ActionSheet actionSheet, int which) {
                            industryId = industry.getIndustryList().get(which).getIndustryId();
                            tv_industry.setText(industry.getIndustryList().get(which).getIndustryName());
                        }
                    }).show();
        }
    }

    private void publishPPT() {
        if (!isSelectPhoto) {
            HashMap<String, String> params = new HashMap<>();
            params.put("task", "postPPTUrl");
            params.put("pptTitle", pptTitle);
            params.put("pptKeyword", pptKeyWord);
            params.put("pptUrl", pptUrl);
            params.put("shares", shares);
            params.put("industryId", industryId + "");

            pptModel.CommonRequest(params).doOnSubscribe(new Action0() {
                @Override
                public void call() {
                    showProgress();
                }
            }).subscribe(new CommonSubscriber<BaseBean>() {
                @Override
                public void onSuccess(BaseBean response) {
                    hideProgress();
                    App.GetInstance().finishClassActivity(PPTTitleKeywordActivity.class);
                    App.GetInstance().finishActivity(SelectPPTIndustry.this);
                }

                @Override
                public void onFailure(BaseBean response) {
                    hideProgress();
                    ToastUtils.showShortToast(SelectPPTIndustry.this, response.getDesc());
                }
            });
        } else {
            requestPPTID();
        }
    }


    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/PPTWorld/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    private void requestPPTID() {
        if (TextUtils.isEmpty(pptId)) {
            HashMap<String, String> params = new HashMap<>();
            params.put("pptTitle", pptTitle);
            params.put("pptKeyword", pptKeyWord);
            params.put("industryId", industryId + "");
            params.put("shares", shares);
            params.put("task", "getImgPPTId");

            pptModel.RequestImageId(params).subscribe(new CommonSubscriber<PPTResponseBean>() {
                @Override
                public void onSuccess(PPTResponseBean response) {
                    pptId = response.getPptId() + "";
                    requestPPTID();
                }

                @Override
                public void onFailure(BaseBean response) {
                    ToastUtils.showShortToast(SelectPPTIndustry.this, response.getDesc());
                }
            });
        } else {
            File upload_file = new File(paths.get(0));
            Luban.with(this).load(upload_file).ignoreBy(100).setTargetDir(getPath()).setCompressListener(new OnCompressListener() { //设置回调
                @Override
                public void onStart() {
                    // TODO 压缩开始前调用，可以在方法内启动 loading UI
                }

                @Override
                public void onSuccess(File file) {
                    // TODO 压缩成功后调用，返回压缩后的图片文件
                    File local_File = file;
                    String isLast = "n";
                    if (paths.size() == 1) {
                        isLast = "y";
                    } else {
                        isLast = "n";
                    }
                    RetrofitUploadFileParameterBuilder.newBuilder().cleanParams();
                    Map<String, RequestBody> params_requestbody = RetrofitUploadFileParameterBuilder.newBuilder()
                            .addParameter("pptId", pptId)
                            .addParameter("file", local_File)
                            .addParameter("isLast", isLast)
                            .addParameter("task", "postPPTImg")
                            .addParameter("f", "android")
                            .addParameter("language", "zh_cn")
                            .addParameter("countryCode", "+86")
                            .addParameter("version", DeviceUtils.getVersionName())
                            .addParameter("userId", PreferenceUtils.GetUserId())
                            .addParameter("token", PreferenceUtils.GetUserToken())
                            .addParameter("phoneId", DeviceUtils.GetDevcieId())
                            .addParameter("appVersion", DeviceUtils.getVersionName())
                            .bulider();
                    pptModel.PublishPPTWithPic(params_requestbody).doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            showProgress();
                        }
                    }).subscribe(new CommonSubscriber<BaseBean>() {
                        @Override
                        public void onSuccess(BaseBean response) {
                            paths.remove(0);
                            if (paths.size() > 0) {
                                requestPPTID();
                            } else {
                                hideProgress();
                                App.GetInstance().finishClassActivity(PPTTitleKeywordActivity.class);
                                App.GetInstance().finishActivity(SelectPPTIndustry.this);
                                App.GetInstance().finishClassActivity(SelectPhotoActivity.class);
                            }
                        }

                        @Override
                        public void onFailure(BaseBean response) {
                            hideProgress();
                            ToastUtils.showShortToast(SelectPPTIndustry.this, response.getDesc());
                        }
                    });
                }

                @Override
                public void onError(Throwable e) {
                    // TODO 当压缩过程出现问题时调用
                }
            }).launch();
        }
    }
}
